#include "global.hpp"
#include <stdexcept>

namespace sympy
{
    using namespace baltam::py;
    PyObject *sp = 0;

    PyObject *S = 0;
    PyObject *Symbol = 0;
    PyObject *Matrix = 0;
    PyObject *Function = 0;

    PyObject *symbols = 0;
    PyObject *simplify = 0;

    PyObject *Integer = 0;
    PyObject *Rational = 0;
    PyObject *Float = 0;

    int initialize()
    {
        InitializePyRoot();
        sp = pyimport_import_module("sympy");
        if (sp == nullptr)
            bxErrMsgTxt("导入 sympy 模块失败，请手动安安装：pipcmd('install sympy').");
        S = pyobject_get_attr_string(sp, "S");
        Symbol = pyobject_get_attr_string(sp, "Symbol");
        Matrix = pyobject_get_attr_string(sp, "Matrix");
        Function = pyobject_get_attr_string(sp, "Function");

        symbols = pyobject_get_attr_string(sp, "symbols");
        simplify = pyobject_get_attr_string(sp, "simplify");

        Integer = pyobject_get_attr_string(sp, "Integer");
        Rational = pyobject_get_attr_string(sp, "Rational");
        Float = pyobject_get_attr_string(sp, "Float");

        return 0;
    }

    void finalize()
    {
        if (sp != nullptr)
        {
            py_dec_ref(S);
            py_dec_ref(Symbol);
            py_dec_ref(Matrix);
            py_dec_ref(Function);

            py_dec_ref(symbols);
            py_dec_ref(simplify);

            py_dec_ref(Integer);
            py_dec_ref(Rational);
            py_dec_ref(Float);

            py_dec_ref(sp);
            sp = nullptr;
        }
    }

    void bxGetSymPy(int nlhs, bxArray *plhs[], int nrhs, const bxArray *prhs[])
    {
        py_inc_ref(sp);
        plhs[0] = bxCreateCStruct(pyobject_sid, sp);
    }

} // namespace symbolic
